package com.thlws.study.rabbitmq.internal.receiver;

import com.rabbitmq.client.Channel;
import com.thlws.study.rabbitmq.internal.RmqConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author HanleyTang 2019-06-23
 */
@Component
public class SimpleReceiver {

    private final Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 声明队列 queue0 并关联 死信队列
     * 业务队列(queue0) 绑定 死信队列
     *
     * 也可以使用 @Queue->@Argument 注解 绑定死信队列
     *
     */
    @Bean
    public org.springframework.amqp.core.Queue queue0(){
        return QueueBuilder.durable("queue0")
                .withArgument("x-dead-letter-exchange", RmqConst.dead_letter_exchange)
                .withArgument("x-dead-letter-routing-key", RmqConst.dead_letter_routing_key)
                .build();
    }


    @RabbitListener(queues = {"queue0"})
    public void queue0(Message message, Channel channel) throws IOException {
        try {
            logger.info("queue0 接收消息 :{}",new String(message.getBody()));
            int v = 0/0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            logger.error("消息确认失败.");
            //hannel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);

            //注意要抛出异常，消息才会重发.
            //throw e;
        }
    }


    /***
     * 自动创建Queue
     * 会绑定默认的 exchange 和 routing key
     */
    @RabbitListener(queuesToDeclare = @Queue("queue1"))
    public void queue1(Message message, Channel channel) throws IOException {
        logger.info("queue1 接收消息 :{}",new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    /***
     * 不会自动创建Queue
     * 手动确认消息
     */
    @RabbitListener(queues = {"queue2"})
    public void queue2(Message message, Channel channel) throws IOException {
        try {
            logger.info("queue2 接收消息 :{}",new String(message.getBody()));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            logger.error("消息确认失败.");
            throw e;
        }
    }


}
